package jsyf.oa.service.device;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.device.DeviceBucketDao;
import jsyf.oa.entity.device.DeviceBucketEntity;
import jsyf.oa.facade.device.DeviceBucketFacade;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by y on 2018/7/5.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class DeviceBucketService implements DeviceBucketFacade {
    @Autowired
    private DeviceBucketDao deviceBucketDao;
    @Override
    public JSONObject getListBymodelId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String modelId=jsonParams.getString("modelId");
        JSONObject obj=new JSONObject();
        List<JSONObject> buckets=deviceBucketDao.getJSONListByCondition(" AND MODEL_ID=?",new Object[]{modelId});
        obj.put("buckets",buckets);
        return obj;
    }

    @Override
    public String add(String jsonObject) {
        List<DeviceBucketEntity> entity = (List<DeviceBucketEntity>) JSONArray.toCollection(JSONArray.fromObject(jsonObject), DeviceBucketEntity.class);
        if (entity.size()>0){
            deviceBucketDao.removeByCondition("AND MODEL_ID=?",
                    new String[]{entity.get(0).getModelId()});
            for (int i = 0; i < entity.size(); i++) {
                DeviceBucketEntity model = entity.get(i);
                deviceBucketDao.add(model);
            }
        }
        return "true";

    }

    @Override
    public Boolean delById(String jsonData) {
        return deviceBucketDao.delById(JSON.parseObject(jsonData).getString("id")) > 0;
    }
}
